<template>
    <el-form :model="activityForm" :inline="true" style="margin-bottom: 10px;" class="demo-form-inline">
        <el-form-item label="团建名称">
            <el-input v-model="activityForm.teamBuildingName" style="width: 120px;" placeholder="请输入团建名称" />
        </el-form-item>
        <el-form-item label="活动状态">
            <el-select v-model="activityForm.activityStatus" clearable style="width: 100px;" placeholder="请选择">
                <el-option label="正在进行" value="1"></el-option>
                <el-option label="已经结束" value="2"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="开展时间">
            <el-date-picker v-model="activityForm.date" clearable value-format="YYYY-MM-DD" type="daterange"
                placeholder="选择日期" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                style="width: 300px; margin-left: 10px"></el-date-picker>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getTeamBuildingList">查询</el-button>
            <el-button type="info" @click="clearActivityForm">清空</el-button>
        </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="userTableData" border style="width: 100%;margin-bottom: 10px;margin-top: 10px;">
        <el-table-column type="index" label="id" width="40" />
        <el-table-column property="teamBuildingName" label="团建名称" width="120" />
        <el-table-column property="maxCapacity" label="人数上限" width="120" />
        <el-table-column property="actualAttendance" label="实时参加人数" width="120" />
        <el-table-column property="startTime" label="开展时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
        </el-table-column>
        <el-table-column property="endTime" label="结束时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
        </el-table-column>
        <el-table-column property="activityStatus" label="活动状态" width="120">
            <template #default="scope">
                <el-tag v-if="scope.row.activityStatus === 1" type="success">进行中</el-tag>
                <el-tag v-if="scope.row.activityStatus === 2" type="info">已结束</el-tag>
            </template>
        </el-table-column>
        <el-table-column property="registrationStatus" label="报名状态" width="120">
            <template #default="scope">
                <el-tag v-if="scope.row.registrationStatus == 1" type="success">已报名</el-tag>
                <el-tag v-if="scope.row.registrationStatus == 2" type="info">未报名</el-tag>
            </template>
        </el-table-column>
        <el-table-column style="justify-content: space-between;" label="操作">
            <template #default="scope">
                <el-link type="primary" style="margin-right: 10px;"
                    @click="registration(scope.row.id, scope.row.teamBuildingName, scope.row.maxCapacity, scope.row.actualAttendance)">报名</el-link>
                <el-link target="_blank" style="margin-right: 10px;" @click="getDetail(scope.row.id)">查看详情</el-link>
                <el-link type="danger" @click="cancelRegistration(scope.row.id)">取消报名</el-link>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
        :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <!-- 报名 -->
    <el-dialog v-model="registerDialogVisible" title="团建活动报名" draggable center style="width: 50%;">
        <el-card style="width: 50%;margin-left: 150px;">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="团建名称" prop="teamBuildingName">
                    <el-input v-model="ruleForm.teamBuildingName" placeholder="请输入团建名称" style="width: 170px;" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请输入你的姓名" style="width: 170px;" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="ruleForm.gender" clearable style="width: 170px;" placeholder="请选择">
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="账号" prop="account">
                    <el-input v-model="ruleForm.account" placeholder="请输入你的账号" style="width: 170px;" />
                </el-form-item>
                <el-form-item label="报名时间" prop="registrationTime">
                    <el-date-picker v-model="ruleForm.registrationTime" type="date" value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择报名时间" style="width: 170px;" :size="size" />
                </el-form-item>
                <el-form-item style="justify-items: center;">
                    <el-button type="primary" @click="register">确定</el-button>
                    <el-button @click="resetForm(ruleFormRef)">清空</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-dialog>
    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="查看详情" draggable center>
        <el-form :model="form" label-width="auto" style="max-width: 100%">
            <el-form-item label="团建名称:">
                {{ form.teamBuildingName }}
            </el-form-item>
            <el-form-item label="你的活动时长:">
                {{ form.activityDuration }}
            </el-form-item>
        </el-form>
    </el-dialog>
</template>


<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { empAccount } from '@/store'
import axios from '@/utils/request'
import moment from 'moment'
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const registerDialogVisible = ref(false)
const cancelDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const size = ref<ComponentSize>('default')
const total = ref(0)
const background = ref(true)
const disabled = ref(false)
const name = ref(empAccount().$state.name)
const account = ref(empAccount().$state.account)
const gender = ref(empAccount().$state.gender)
const ruleForm = reactive({
    id: '',
    teamBuildingName: '',
    name: '',
    gender: '',
    account: '',
    registrationTime: ''
})
const form = ref({
    teamBuildingName: '',
    activityDuration: ''
})
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '姓名不能为空', trigger: 'blur' },
    ],
    account: [
        { required: true, message: '账号不能为空', trigger: 'blur', },
    ],
    registrationTime: [
        { required: true, message: '时间不能为空', trigger: 'change', },
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change', },
    ],
    teamBuildingName: [
        { required: true, message: '团建名称不能为空', trigger: 'blur', },
    ],
})

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
let activityForm = ref({
    teamBuildingName: '',
    activityStatus: '',
    date: ['', ''],
})
const clearActivityForm = () => {
    activityForm.value = {
        teamBuildingName: '',
        activityStatus: '',
        date: ['', ''],
    }
}
const userTableData = ref([])
//当前页数发送变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    //重新获取列表
    getTeamBuildingList()
}
//当前展示页数
const handleSizeChange = (val: number) => {
    pageSize.value = val
    //重新获取列表
    getTeamBuildingList()
}
const registration = (id: any, teamBuildingName: string, maxCapacity: any, actualAttendance: any) => {
    //判断人数是否已满
    if (actualAttendance >= maxCapacity) {
        ElMessage.error('人数已满')
        return
    }
    //显示对话框
    registerDialogVisible.value = true
    //设置团建名称
    ruleForm.teamBuildingName = teamBuildingName
    //设置id
    ruleForm.id = id
    //设置姓名
    ruleForm.name = name.value
    //设置账号
    ruleForm.account = account.value
    //设置性别
    ruleForm.gender = gender.value == '1' ? '1' : '2'
    //设置时间
    ruleForm.registrationTime = moment().format('YYYY-MM-DD HH:mm:ss')
}
//获取团建活动列表
const getTeamBuildingList = async () => {
    try {
        //发送请求
        const result = await axios.get('/emp/teamBuildingActivities', {
            params: {
                teamBuildingName: activityForm.value.teamBuildingName,
                activityStatus: activityForm.value.activityStatus,
                start: activityForm.value.date[0],
                end: activityForm.value.date[1],
                page: currentPage.value,
                pageSize: pageSize.value,
                account: account.value
            }
        })
        if (result.data.code === 1) {
            userTableData.value = result.data.data.rows
            total.value = result.data.data.total
            if (activityForm.value.date[0] !== '' || activityForm.value.date[1] !== '' || activityForm.value.activityStatus !== ''
                || activityForm.value.teamBuildingName !== '') {
                ElMessage.success('查询成功')
            }
        } else {
            ElMessage.error('查询失败')
        }
    } catch (error) {
        console.error('查询团建活动列表失败', error);
        ElMessage.error('查询失败，请稍后再试');
    }
}
//团建活动报名
const register = async () => {
    //信息校验
    if (ruleForm.account === '') {
        ElMessage.error('请输入账号')
        return
    }
    if (ruleForm.name === '') {
        ElMessage.error('请输入姓名')
        return
    }
    if (ruleForm.gender === '') {
        ElMessage.error('请选择性别')
        return
    }
    if (ruleForm.registrationTime === '') {
        ElMessage.error('请选择时间')
        return
    }
    if (ruleForm.teamBuildingName === '') {
        ElMessage.error('请输入团建名称')
        return
    }
    //判断人数是否已满

    try {
        //发送请求
        const result = await axios.post('/emp/teamBuildingActivity', ruleForm)
        if (result.data.code === 1) {
            ElMessage.success('报名成功')
            //关闭对话框
            registerDialogVisible.value = false
            //重新获取列表
            getTeamBuildingList()
        } else {
            ElMessage.error(result.data.message)
        }
    } catch (error) {
        console.error('团建活动报名失败', error);
        ElMessage.error('报名失败，请稍后再试');
    }
}
//获取详情
const getDetail = async (id: any) => {
    //显示对话框
    detailDialogVisible.value = true
    try {
        //发送请求
        const result = await axios.get('/emp/teamBuildingActivity', {
            params: {
                id: id,
                account: account.value
            }
        })
        if (result.data.code === 1) {
            form.value = result.data.data
            detailDialogVisible.value = true
        } else {
            ElMessage.error(result.data.message)
        }
    } catch (error) {
        console.error('获取详情失败', error);
        ElMessage.error('获取详情失败，请稍后再试');
    }
}
//取消报名
const cancelRegistration = async (id: any) => {
    const isConfirm = window.confirm('确定取消报名吗？')
    if (!isConfirm) {
        return
    }
    try {
        //发送请求
        const result = await axios.delete('/emp/teamBuildingActivity', {
            params: {
                id: id,
                account: account.value
            }
        })
        if (result.data.code === 1) {
            ElMessage.success('取消报名成功')
            //关闭对话框
            cancelDialogVisible.value = false
            //重新获取列表
            getTeamBuildingList()
        } else {
            ElMessage.error(result.data.message)
        }
    } catch (error) {
        console.error('取消报名失败', error);
        ElMessage.error('取消报名失败，请稍后再试');
    }
}
</script>

<style></style>